package com.hadluo.qq.client.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hadluo.qq.client.model.FriendListItem;
import com.hadluo.qq.client.model.Group;
import com.hadluo.qq.client.model.GroupMessage;
import com.hadluo.qq.client.model.UserInfo;
import com.hadluo.qq.client.utils.Constants;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class GroupListPanel extends JPanel {
    private JList<Group> groupList;
    private DefaultListModel<Group> groupListModel;
    private UserInfo currentUser;
    private SimpleDateFormat timeFormat;

    public GroupListPanel(UserInfo currentUser) {
        this.currentUser = currentUser;
        this.timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        initializeUI();
        loadGroupList();
    }

    public void onMessageReceived (GroupMessage groupMessage){
        // 更新好友列表中的最后一条消息
        for (int i = 0; i < groupListModel.size(); i++) {
            Group item = groupListModel.getElementAt(i);
            if (item.getId().equals(groupMessage.getGroupId())) {
                item.setLastMessage(groupMessage.getContent());
                item.setLastMessageTime(groupMessage.getCreateTime().getTime());
                groupList.repaint();
                break;
            }
        }
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setBackground(new Color(35, 35, 35));

        // 创建个性签名面板
        JPanel signaturePanel = new JPanel(new BorderLayout());
        signaturePanel.setBackground(new Color(35, 35, 35));
        signaturePanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JLabel signatureLabel = new JLabel("群列表");
        signatureLabel.setForeground(Color.WHITE);
        signatureLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

        signaturePanel.add(signatureLabel, BorderLayout.CENTER);

        // 创建群列表
        groupListModel = new DefaultListModel<>();
        groupList = new JList<>(groupListModel);
        groupList.setBackground(new Color(35, 35, 35));
        groupList.setForeground(Color.WHITE);
        groupList.setSelectionBackground(new Color(45, 45, 45));
        groupList.setSelectionForeground(new Color(29, 185, 84));
        groupList.setBorder(null);
        groupList.setCellRenderer(new GroupListCellRenderer());

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(groupList);
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() {
            @Override
            protected void configureScrollBarColors() {
                this.thumbColor = new Color(29, 185, 84);
                this.trackColor = new Color(45, 45, 45);
            }
        });
        add(signaturePanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

        // 添加双击事件监听器
        groupList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    Group selectedGroup = groupList.getSelectedValue();
                    if (selectedGroup != null) {
                        openGroupChat(selectedGroup);
                    }
                }
            }
        });
    }

    private void loadGroupList() {
        new Thread(() -> {
            try {
                String url = "http://"+ Constants.SERVER_HOST+":8080/api/group/list?qqNumber=" + currentUser.getQqNumber();
                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("GET");

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        JSONObject jsonResponse = JSON.parseObject(response.toString());
                        if (jsonResponse.getBoolean("success")) {
                            JSONArray groups = jsonResponse.getJSONArray("data");
                            List<Group> groupList = new ArrayList<>();
                            for (int i = 0; i < groups.size(); i++) {
                                Group group = JSON.parseObject(groups.getJSONObject(i).toString(), Group.class);
                                groupList.add(group);
                            }

                            SwingUtilities.invokeLater(() -> {
                                groupListModel.clear();
                                for (Group group : groupList) {
                                    groupListModel.addElement(group);
                                }
                            });
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                            "加载群列表失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }

    private void openGroupChat(Group group) {
        // 创建群聊窗口
        JFrame chatFrame = new JFrame(group.getGroupName());
        chatFrame.setSize(800, 600);
        chatFrame.setLocationRelativeTo(null);

        // 创建群聊面板
        GroupChatPanel chatPanel = new GroupChatPanel(group, currentUser);

        chatFrame.add(chatPanel);
        chatFrame.setVisible(true);
    }

    // 群列表单元格渲染器
    private class GroupListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            Group group = (Group) value;
            JPanel panel = new JPanel(new BorderLayout(10, 0));
            panel.setBackground(isSelected ? new Color(45, 45, 45) : new Color(35, 35, 35));
            panel.setBorder(new EmptyBorder(10, 10, 10, 10));

            // 创建群头像标签
            JLabel avatarLabel = new JLabel();
            avatarLabel.setPreferredSize(new Dimension(40, 40));
            avatarLabel.setBackground(new Color(60, 60, 60));
            avatarLabel.setOpaque(true);
            avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
            avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
            avatarLabel.setForeground(Color.WHITE);

            // 设置群头像或显示群名首字
            if (group.getAvatar() != null && !group.getAvatar().isEmpty()) {
                try {
                    String avatarUrl = group.getAvatar();
                    if (!avatarUrl.startsWith("http")) {
                        avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                    }
                    ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                    Image image = imageIcon.getImage().getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                    avatarLabel.setIcon(new ImageIcon(image));
                } catch (Exception e) {
                    avatarLabel.setText(group.getGroupName().substring(0, 1));
                }
            } else {
                avatarLabel.setText(group.getGroupName().substring(0, 1));
            }

            // 创建群信息面板
            JPanel infoPanel = new JPanel(new GridLayout(2, 1, 0, 5));
            infoPanel.setBackground(panel.getBackground());

            // 群名称
            JLabel nameLabel = new JLabel(group.getGroupName());
            nameLabel.setForeground(isSelected ? new Color(29, 185, 84) : Color.WHITE);
            nameLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));

            // 最后一条消息
            JLabel lastMessageLabel = new JLabel(group.getLastMessage() != null ? group.getLastMessage() : "暂无消息");
            lastMessageLabel.setForeground(new Color(153, 153, 153));
            lastMessageLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

            infoPanel.add(nameLabel);
            infoPanel.add(lastMessageLabel);

            // 创建时间标签
            JLabel timeLabel = new JLabel();
            if (group.getLastMessageTime() != null) {
                timeLabel.setText(timeFormat.format(group.getLastMessageTime()));
            }
            timeLabel.setForeground(new Color(153, 153, 153));
            timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

            panel.add(avatarLabel, BorderLayout.WEST);
            panel.add(infoPanel, BorderLayout.CENTER);
            panel.add(timeLabel, BorderLayout.EAST);

            return panel;
        }
    }

    public void refreshGroupList() {
        loadGroupList();
    }

    private static class CustomScrollBarUI extends javax.swing.plaf.basic.BasicScrollBarUI {
        @Override
        protected JButton createDecreaseButton(int orientation) {
            return createZeroButton();
        }

        @Override
        protected JButton createIncreaseButton(int orientation) {
            return createZeroButton();
        }

        private JButton createZeroButton() {
            JButton button = new JButton();
            button.setPreferredSize(new Dimension(0, 0));
            return button;
        }

        @Override
        protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
            if (thumbBounds.isEmpty() || !scrollbar.isEnabled()) {
                return;
            }

            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(100, 100, 100));
            g2.fillRoundRect(thumbBounds.x, thumbBounds.y, thumbBounds.width, thumbBounds.height, 8, 8);
            g2.dispose();
        }

        @Override
        protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setColor(new Color(45, 45, 45));
            g2.fillRect(trackBounds.x, trackBounds.y, trackBounds.width, trackBounds.height);
            g2.dispose();
        }
    }
}